package com.demo.web.modules.file;

import com.demo.common.result.ResponseInfo;
import com.demo.common.result.ResultVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.demo.common.util.file.FileNameUtils;
import com.demo.common.util.file.FileUploadUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/file/image")
public class ImageController {
    //服务器存储文件路径
    @Value("${file.saveFilePath}")
    private String saveFilePath;

    //图片文件夹
    @Value("${file.imageDirectory}")
    private String imageDirectory;

    //虚拟路径
    @Value("${file.virtualPath}")
    private String virtualPath;

    //服务器端口
    @Value("${server.port}")
    private Integer svrPort;

    @GetMapping("/test")
    public String test(){
        return "hello, you are in upload test!";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResultVo upload(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> files = multipartRequest.getFileMap();
        List<String> urls = new ArrayList<>();

        for (Map.Entry<String, MultipartFile> entry : files.entrySet())  {
            //取出文件名
            String fileName = entry.getValue().getOriginalFilename();

            //重新生成文件名
            String newFileName = FileNameUtils.getFileName(fileName);

            //存储文件路径
            String newFilePath = this.saveFilePath + this.imageDirectory;
            //System.out.print(newFileName);
            if (FileUploadUtils.upload(entry.getValue(), newFilePath, newFileName) == true) {
                String virtualPath = request.getScheme() + "://" + request.getServerName() + ":" + Integer.toString(this.svrPort) + "/" +
                                        this.virtualPath + this.imageDirectory + newFileName;
                urls.add(virtualPath);
                System.out.print("ok");
            }
            else {
                System.out.print("error");
            }

        }

        return ResponseInfo.<List<String>>success(urls);
    }

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        //得到图片存储路径
        String filePath = this.saveFilePath + this.imageDirectory + fileName;
        File file = new File(filePath);

        //判断文件是否存在
        if(file.exists()){
            response.reset();
            //文件流：字节流。
            response.setContentType("application/octet-stream");
            //为避免字节流、字符流混乱统一设置为字节流
            response.setCharacterEncoding("UTF-8");
            //设置文件类型，浏览器调用不同内嵌程序
            response.setContentType("image/jpg");

            try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
                //下载不打开,配置UTF-8编码
                response.setHeader("Content-Disposition", "attachment;filename=" +
                        URLEncoder.encode(fileName, "UTF-8"));

                //读取文件，写入文件流
                byte[] buff = new byte[1024];
                OutputStream os  = response.getOutputStream();
                int i = 0;
                while ((i = bis.read(buff)) != -1) {
                    os.write(buff, 0, i);
                    os.flush();
                }
            } catch (IOException e) {
                //log.error("{}",e);
                System.out.print(e);
            }
            System.out.print("文件下载成功！");
        } else {
            System.out.print("文件不存在！");
        }
    }
}
